import { isReferee } from "@/func";
import { Player } from "@minecraft/server";
import { SAPIGameConfig } from "@sapi-game/config";
import { Game, GameComponent } from "@sapi-game/main";
import { DimensionIds, EntityTypeIds } from "@sapi-game/utils/vanila-data";
import { CvSBackState } from "./backState";

export class CvSStarter extends GameComponent<CvSBackState> {
    override onAttach(): void {
        this.subscribe(
            Game.events.buttonPush,
            (t) => {
                const p = t.source as Player;
                if (!isReferee(p)) {
                    p.sendMessage("你不是裁判，无法开始本游戏");
                    return;
                }
                if (!this.checkPlayers()) {
                    return p.sendMessage("人数不足，无法开始");
                }
                this.state.start();
            },
            {
                dimensionId: DimensionIds.Overworld,
                loc: [34, -60, 61],
                sourceType: EntityTypeIds.Player,
            }
        );
    }

    checkPlayers() {
        if (SAPIGameConfig.config.debugMode) {
            return (
                this.state.chicken.validSize + this.state.shepherd.validSize >=
                1
            );
        }
        return (
            this.state.chicken.validSize >= 1 &&
            this.state.shepherd.validSize >= 1
        );
    }
}
